package study.week05.gateway.config.jms;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import study.week05.gateway.entity.GatewayContext;
import study.week05.gateway.outbound.JmsHandler;

/**
 * 监听Backend服务的响应<br/>
 * 然后将响应返回给浏览器
 */
@Component
public class ResponseReceiver {

    @Autowired
    JmsHandler jmsHandler;
    /**
     * 监听01
     */
    @JmsListener(destination = "${gateway.response.server01}")
    public void getQueue1(String info) {
        doReceive(info);
    }
    /**
     * 监听02
     */
    @JmsListener(destination = "${gateway.response.server02}")
    public void getQueue2(String info) {
        doReceive(info);
    }

    public void doReceive(String info) {
        String[] split = info.split(":");
        //截取请求的uid和响应
        String uid = split[0];
        String response = split[1];
        //拼接结果
        GatewayContext gatewayContext = jmsHandler.getGatewayContext(uid);
        if(gatewayContext ==null)
        {
            return;
        }
        FullHttpRequest fullRequest = gatewayContext.getFullRequest();
        ChannelHandlerContext ctx = gatewayContext.getCtx();
        //拼接响应、AOP过滤器
        FullHttpResponse httpResponse = jmsHandler.receiveResponse(fullRequest, ctx, response);
        //返回
        jmsHandler.doResponse(fullRequest, ctx,httpResponse);
    }


}
